#include "headers/ScreenCapture.h"
#include <QScreen>
#include <QGuiApplication>
#include <QDateTime>
#include <QDir>
#include <QDebug>

ScreenCapture::ScreenCapture(QObject *parent)
    : QObject(parent)
{
}

QString ScreenCapture::generateFilePath(const QString &processName)
{
    QString dirPath = "D:/MonitoringScreenshots/";
    QDir dir(dirPath);
    if (!dir.exists()) {
        if (dir.mkpath(dirPath)) {
            qDebug() << "[ScreenCapture] 已创建截图存储目录:" << dirPath;
        } else {
            qDebug() << "[ScreenCapture] 截图目录创建失败，使用当前目录";
            dirPath = QDir::currentPath() + "/MonitoringScreenshots/";
            dir.mkpath(dirPath);
        }
    }

    QString timeStamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss_zzz");
    QString fileName = QString("Device_001_%1_%2.png").arg(processName).arg(timeStamp);

    return dirPath + fileName;
}

// 执行截屏操作
void ScreenCapture::captureScreen(const QString &processName)
{
    QScreen *screen = QGuiApplication::primaryScreen();
    if (!screen) {
        qDebug() << "[ScreenCapture] 无法获取屏幕对象，截屏失败";
        return;
    }

    QPixmap screenshot = screen->grabWindow(0);

    QString filePath = generateFilePath(processName);
    if (screenshot.save(filePath, "PNG", 90)) {
        qDebug() << "[ScreenCapture] 截屏成功，路径:" << filePath;
        emit captureFinished(filePath);
    } else {
        qDebug() << "[ScreenCapture] 截屏保存失败，路径:" << filePath;
    }
}
